#include <algorithm>
#include <cstdio>
#include <set>
using namespace std;

int n, ans;
set<int> low;
set<int> big;

int main() {
	freopen("TURNOVER.in", "r", stdin);
	freopen("TURNOVER.out", "w", stdout);
	scanf("%d", &n);
	int tmp;
	scanf("%d", &tmp);
	ans += tmp;
	low.insert(-tmp);
	big.insert(tmp);
	for (int i = 1; i < n; ++i) {
		scanf("%d", &tmp);
		set<int>::iterator i_low = low.lower_bound(-tmp);
		set<int>::iterator i_big = big.lower_bound(tmp);
		if (i_low == low.end()) {
			--i_low;
		}
		if (i_big == big.end()) {
			--i_big;
		}
		ans += min(abs(tmp + *i_low), abs(tmp - *i_big));
		big.insert(tmp);
		low.insert(-tmp);
	}
	printf("%d", ans);
	fclose(stdin);
	fclose(stdout);
	return 0;
}